#!/usr/bin/tcl


set ifn "gen_drv.tr0"
set data ""
set ofn "test.csv"


set IFH [open $ifn "r"]
while { ![eof $IFH] } {
  append data [gets $IFH]
}
close $IFH

set data [split $data]
set header [lrange $data 0 end-1]
set data [lindex $data end]

### Remove enpty list items from header
set tmp $header
set header ""
foreach item $tmp {
  if { $item != "" } {
    lappend header $item
  }
}

### remove copyright from header
for { set i 0 } { $i < [llength $header] } { incr i } {
  if { [lindex $header $i] == "0" } {
    set header [ lrange $header [expr $i +1] end ]
    break
  }
}

### remove all before TIME
for { set i 0 } { $i < [llength $header] } { incr i } {
  if { [lindex $header $i] == "TIME" } {
    set header [ lrange $header $i end-1 ]
    break
  } else {
    continue
  }
  puts "TIME not found in .tr# file."
  exit 1
}

### Parse data
set data_length [regexp -all {(0|\-)\.\d{5}E(\+|\-)\d{2}} $data]
set data_size [expr [string length $data] / $data_length ]
set tmp $data
set data ""
for { set i 0 } { $i < $data_length } { incr i } {
  set first [ expr $i * $data_size ]
  set last  [ expr $first + $data_size - 1]
  lappend data [string range $tmp $first $last]
}

set OFH [ open $ofn "w" ]

foreach tt $header {
  puts -nonewline $OFH "\t$tt"
}
puts $OFH ""

for { set i 0 } { $i < $data_length } { incr i [llength $header] } {
  foreach tt [lrange $data $i [expr $i + [llength $header] - 1 ] ] {
    puts -nonewline $OFH "\t$tt"
  }
  puts $OFH ""
}
close $OFH

#puts $data_size
#puts $header
#foreach d $data {
#  puts $d
#}

exit 0
